package com.zkj.controller.admin;
import com.zkj.constant.MessageConstant;
import com.zkj.exception.FileIsEmptyException;
import com.zkj.result.Result;
import io.swagger.annotations.ApiModel;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.joda.time.DateTime;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author: zhangKaiJun
 * @createTime：2024/8/27
 * @description：
 */
@ApiModel(value = "公共接口")
@RestController
@RequestMapping("/admin/common")
public class CommonController {
    // 上传接口
    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new FileIsEmptyException(MessageConstant.FILEISEMPTY);
        }

        try {

            // 获取用户主目录
            String userHome = System.getProperty("user.home");
            // 拼接桌面路径
            String desktopPath = userHome + "/Desktop/files";
            // 将文件保存到指定路径
            File directory = new File(desktopPath);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            //在文件名称前面添加uuid值
            String key = UUID.randomUUID().toString().replaceAll("-","")
                    +file.getOriginalFilename();
            //对上传文件分组，根据当前日期  /2022/11/11
            String dateTime = new DateTime().toString("yyyyMMdd");
            key = dateTime+key;

            file.transferTo(new File(directory, key));

            return Result.success(key).message("文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("文件上传失败");
        }
    }
}
